import { SelectOutlined } from '@ant-design/icons';
import { Input } from 'antd';
import React, { useCallback } from 'react';
import SearchTable from './SearchTable';
import useModal from './useModal';

function noop() { }

export default function PopupSelect({ title, field, columns, onLoad, placeholder, value, onChange = noop, inputProps, ...props }) {
  const [modal, modalHolder] = useModal();
  const [inputValue, setInputValue] = React.useState(value);

  const handleChange = useCallback((record) => {
    setInputValue(record?.[field]);
    onChange(record?.[field], record);
  }, [field, onChange]);

  const handleClick = useCallback(() => {
    let selected = null;
    const handle = modal.open({
      title,
      width: '80%',
      content: <SearchTable columns={columns} onLoad={onLoad} placeholder={placeholder}
        onSelect={record => selected = record}
        onSelectEnd={(record = {}) => {
          handle.destroy();
          handleChange(record);
        }}
      />,
      onOk() {
        if (!selected) return false;
        handleChange(selected);
      }
    });
  }, [title, columns, handleChange, modal, onLoad, placeholder]);

  return <>
    <Input allowClear addonAfter={<SelectOutlined />} value={value === undefined ? inputValue : value} {...inputProps} {...props}
      onClick={handleClick}
      onChange={e => {
        // allowClear的处理
        if (e.target.value === '') {
          handleChange(null);
        }
      }} />
    {modalHolder}
  </>
}